<template>
	<view class="profile">
		<ws-wx-privacy id="privacy-popup"></ws-wx-privacy>
		<view class="header">
			<image class="header-bg" src="@/static/profile-bg.png" mode="aspectFill"></image>
			<button class="avatar" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
				<van-image
					round
					width="160rpx"
					height="160rpx"
					:src="userInfo.avatar_url"
				/>
			</button>
				
			<view class="nickname" @click="$refs.nicknameDialog.open()">
				{{userInfo.nickname || '请完善姓名'}}
				<view class="tag" v-if="userInfo.role && userInfo.role[0] && userInfo.role[0].role_name">
					<van-tag type="primary">{{userInfo.role[0].role_name}}</van-tag>
				</view>
				<van-icon name="edit" />
			</view>
		</view>
		
		<van-cell-group title="个人信息" inset>
		  <van-cell title="性别" :value="userInfo.sex || '请完善性别'" @click="isShowPopup = true" is-link />
			<van-cell title="手机号" :value="userInfo.phone || '请完善手机号'" @click="$refs.inputDialog.open()" is-link />
			<button open-type="feedback">
				<van-cell title="反馈" is-link />
			</button>
		  <van-cell title="联系我们" @click="$refs.alertDialog.open()" is-link />
		</van-cell-group>
		
		<van-popup
		  :show="isShowPopup"
		  round
		  position="bottom"
			lock-scroll
			@click-overlay="isShowPopup = false"
		>
			<van-picker show-toolbar :columns="sexList" @confirm="selectSexConfirm" @cancel="isShowPopup = false" />
		</van-popup>
		
		<uni-popup ref="inputDialog" type="dialog">
			<uni-popup-dialog before-close mode="input" title="输入手机号" :value="userInfo.phone"
				placeholder="请输入新的手机号" @close="$refs.inputDialog.close()" @confirm="handlePhoneConfirm"></uni-popup-dialog>
		</uni-popup>
		
		<uni-popup ref="nicknameDialog" type="dialog">
			<uni-popup-dialog before-close type="info" title="输入昵称" @close="(_nickname = '',$refs.nicknameDialog.close())" @confirm="handleNicknameConfirm">
				<input type="nickname" maxlength="7" placeholder="请输入新的昵称" @change="e => _nickname = e.detail.value" @input="e => _nickname = e.detail.value" />
			</uni-popup-dialog>
		</uni-popup>
		
		<uni-popup ref="alertDialog" type="dialog">
			<uni-popup-dialog type="info" cancelText="关闭" confirmText="确定" title="联系我们">
				<view>
					<p v-for="it in phone" :key="it.region">
						{{it.region}}电话: 
						<span class="callPhone" @click="callPhone(it.phone)">{{it.phone}}</span>
						</p>
				</view>
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	import {mapState, mapActions} from 'vuex'
	const db = uniCloud.database()
	const userDB = db.collection('dish-user')
	export default {
		data() {
			return {
				sexList: ['男', '女'],
				isShowPopup: false,
				isShowDialog: false,
				_nickname: ''
			};
		},
		computed: {
			...mapState({
				userInfo: s => s.user.userInfo,
				publicInfo: s => s.user.publicInfo
			}),
			phone() {
				const map = {
					'苏州': 'phone_suzhou',
					'温州': 'phone_wenzhou'
				}
				return Object.entries(map).map(e => ({
					region: e[0],
					phone: this.publicInfo[e[1]]
				}))
			}
		},
		onLoad() {
			wx.getPrivacySetting({
				success: res => {
					if (res.needAuthorization) {
						console.log('需要弹出隐私协议');
					} else {
						console.log('不需要弹出隐私协议');
					}
				},
				fail: () => {},
				complete: () => {}
			})
			wx.requirePrivacyAuthorize({
				success: () => {
						console.log('点击同意');
				},
				fail: () => {
					console.log('点击拒绝');
				}
			})
			// wx.openPrivacyContract({
			//   success: () => {}, // 打开成功
			//   fail: () => {}, // 打开失败
			//   complete: () => {}
			// })
		},
		methods: {
			...mapActions(['updateUserInfo', 'getUserInfo']),
			async onChooseAvatar(e) {
				try{
					const avatarUrl = e.detail.avatarUrl
					const res = await uniCloud.uploadFile({filePath: avatarUrl,cloudPath: Date.now() + '.jpg'})
					if (res.success) {
						this.$store.dispatch('updateUserInfo', {avatar_url: res.fileID})
					}
				}catch(e){
					//TODO handle the exception
				}
			},
			selectSexConfirm(e) {
				const sex = e.detail.value
				this.updateUserInfo({sex})
				this.isShowPopup = false
			},
			async handlePhoneConfirm(e) {
				const phone = e.replace(/[^\d]/g, '')
				const reg = /^(?:(?:\+|00)86)?1\d{10}$/
				if (reg.test(phone)) {
					uni.showLoading({title: '加载中',mask: true});
					await this.updateUserInfo({phone})
					await this.getUserInfo(false)
					this.$refs.inputDialog.close()
					uni.hideLoading()
					uni.$emit('reloadDishData')
				} else {
					uni.showToast({
						title: '手机号格式不正确',
						icon: 'none'
					})
				}
			},
			async handleNicknameConfirm() {
				if (!this._nickname?.trim()) return uni.showToast({icon: 'none', title: '昵称不可为空'})
				uni.showLoading({mask: true,})
				await this.updateUserInfo({nickname: this._nickname})
				this.$refs.nicknameDialog.close()
				uni.hideLoading()
			},
			callPhone(phoneNumber) {
				wx.makePhoneCall({
				  phoneNumber
				})
			}
		}
	}
</script>

<style lang="scss">
	.profile {
		min-height: 100vh;
		background-color: #f4f4f4;
		
		button {
			padding: 0;
			border-radius: 0;
			&::after {
				border: 0;
			}
		}
		.van-cell__title {
			text-align: left;
		}
		
		.header {
			width: 100vw;
			height: 340rpx;
			display: flex;
			align-items: center;
			padding: 20rpx;
			color: white;
			position: relative;
			background-color: $uni-theme-color;
			overflow: hidden;
			
			.header-bg {
				position: absolute;
				left: 0;
				bottom: -40rpx;
				width: 101vw;
				height: 100%;
				z-index: 0;
				filter: blur(4px);
				opacity: 0.3;
			}
			
			.avatar {
				width: 160rpx;
				height: 160rpx;
				border-radius: 50%;
				overflow: hidden;
				z-index: 1;
				padding: 0;
				margin: 0;
				&::after {
					border: 0;
				}
			}
			
			.nickname {
				height: 56rpx;
				font-size: 40rpx;
				margin-left: 20rpx;
				position: relative;
				z-index: 1;
				display: flex;
				align-items: center;
				justify-content: center;
				.tag {
					height: 32rpx;
					margin: 0 20rpx auto 10rpx;
					.van-tag {
						display: block;
					}
				}
			}
		}
		
		.callPhone {
			margin-left: 10rpx;
			color: #409EFF;
		}
	}
</style>